package org.darkbits.cyklon.machine;

import java.lang.reflect.Method;



public class MethodProperty extends AbstractOrderedProperty {
	private Method getter;
	private Method setter;
	private Method value;
	private Machine owner;
	private String name;
	private Class type;
	private int order;
	private float min, max;
	
	public MethodProperty(Machine owner, String name, int order, Method getter, Method setter, Method value, float min, float max)  throws TypeMismatchException {
		this.getter = getter;
		this.setter = setter;
		this.value = value;
		this.owner = owner;
		this.name = name;
		this.order = order;
		this.min = min;
		this.max = max;
		
		findType();
	}	
	
	private void findType() throws TypeMismatchException {
		Class getterClass = getter.getReturnType();
		Class setterClass = setter.getParameterTypes()[0];
		if (getterClass != setterClass) {
			throw new TypeMismatchException("getter and setter type mismatch");
		}
		type = getterClass;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getOrder() {
		return order;
	}

	public void setOrder(int order) {
		this.order = order;
	}

	public Object get() throws PropertyException {
		try {
			return getter.invoke(owner);			
		} catch (Exception e) {
			throw new PropertyException(e);
		}
	}
	
	public void set(Object o) throws PropertyException {
		try {
			setter.invoke(owner, o);
		} catch (Exception e) {
			throw new PropertyException(e);
		} 
	}
	
	public String getValueOf() throws PropertyException {
		try {
			return value.invoke(owner).toString();
		} catch (Exception e) {
			throw new PropertyException(e);
		}
	}

	public Class getType() {
		return type;
	}
	
	public float getMax() {
		return max;
	}

	public float getMin() {
		return min;
	}

	public Machine getOwner() {
		return owner;
	}
}
